$(document).ready(function() {
    
    $("#signin_btn").unbind('click').click(function() {
        var flag = true;
        if (!validate($("#login").val(), "^[a-zA-Z]\\w{2,}$")) {
            flag = false;
        }
        if (!validate($("#password").val(), "\\w{6,14}$")) {
            flag = false;
        }
        if (flag) {
            sendData();
        } else {
            $("#sign_in_res").html("<h3>Wrong login or password format.<br/>Please, try again.</h3>");
        }
    });
    
    function sendData() {
        var dataString = 'login=' + $("#login").val()
                        + '&password=' + $("#password").val();
            $.ajax({
                type: "POST",
                url: "SignIn",
                data: dataString,
                success:  function(data) {
                    if (data.answer === "OK") {
                        window.location.replace("index.jsp");
                    } else {
                        $("#sign_in_res").html("<h3>Wrong login or password.<br/>Please, try again.</h3>");
                    }
                }
            });
    };
    
    function validate(value, pattern) {
        var reg = new RegExp(pattern);
        return reg.test(value);
    };
});